// pages/demo01/demo01.js
Page({
  data:{
      img_src:"",
      img_text:[],
      text:"",
      create_time:"",
      title:"",
      content:""
  },
  titletFs(e){
    this.setData({
      title:e.detail.value
    })
  },
  onEditorReady(){
    const that = this
    wx.createSelectorQuery().select('#editor').context(function(res) {
      that.editorCtx = res.context
      that.editorCtx.setContents({
        html:that.data.content   
      });
    }).exec()
    
  },
  saveFs(){
    this.setData({
      create_time:new Date().toLocaleString()
    })
    wx.cloud.database().collection("note").add({
      data:{
        img_src:this.data.img_src,
        title:this.data.title,
        text:this.data.text,
        content:this.data.content,
        create_time:this.data.create_time,
        type:1,
        Collection:0
      }}).then(res=>{
        wx.switchTab({
          url: '/pages/index/index',
        })
      }).catch(res=>{
          console.log("type=1 的笔记写入失败",res);
      })
  }
  ,
  upImg(){
      let that=this
      wx.chooseImage({
          count: 1,
          sizeType: [ 'compressed'],
          sourceType: ['album', 'camera'],
          success: res => {
            // tempFilePath可以作为img标签的src属性显示图片
            const tempFilePaths = res.tempFilePaths;
            this.uploadFile(tempFilePaths[0]);
            let fileBuffer=wx.getFileSystemManager().readFileSync(tempFilePaths[0]);
            wx.cloud.callFunction({
              name:"OCR_getPrint",
              data:{
                buffer:fileBuffer
              },
              success :res => {
                let items=res.result.items;
                let text=""
                let content=""
                items.forEach(element => {
                  text=text+element.text;
                  content=content+"<p>"+element.text+"</p><p><br></p>";
                });
                that.setData({
                  img_text:items,
                  text,
                  content
                }) 
                this.onEditorReady()
              },
              fail(res){
                console.log("识别失败",res);
              }
            })
            
          }
        })
        
  },
  uploadFile(tempFilePaths){
      wx.cloud.uploadFile({
          cloudPath: new Date().getTime()+'.png', // 上传至云端的路径
          filePath: tempFilePaths, // 小程序临时文件路径
          success: res => {
            // 返回文件 ID
            this.setData({
              img_src:res.fileID
            })
          },
          fail: console.error
        })
  }
})